#import "VideoPlayerView.h"

@interface VideoPlayerView ()

@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) AVPlayerLayer *playerLayer;
@property (nonatomic, strong) NSTimer *progressTimer;
@property (nonatomic, assign) BOOL isFullScreen;
@property (nonatomic, assign) CGRect originalFrame;

@property (nonatomic, strong) UIButton *playPauseButton;
@property (nonatomic, strong) UISlider *progressSlider;
@property (nonatomic, strong) UIButton *fullScreenButton;
@property (nonatomic, strong) UIView *controlView;

@end

@implementation VideoPlayerView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupUI];
        [self setupPlayerObservers];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];
    if (self) {
        [self setupUI];
        [self setupPlayerObservers];
    }
    return self;
}

- (void)dealloc {
    [self removePlayerObservers];
    [self.progressTimer invalidate];
    self.progressTimer = nil;
}

- (void)setupUI {
    // 添加播放器图层
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    self.playerLayer.frame = self.bounds;
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    self.playerLayer.zPosition = -1;
    self.playerLayer.contentsGravity = kCAGravityResizeAspectFill;
    self.playerLayer.cornerRadius = 8.0f;
    self.playerLayer.masksToBounds = YES;
    self.playerLayer.backgroundColor = [UIColor blackColor].CGColor;
    [self.layer addSublayer:self.playerLayer];
    
    // 添加控制视图
    [self addSubview:self.controlView];
    [self.controlView addSubview:self.playPauseButton];
    [self.controlView addSubview:self.progressSlider];
    [self.controlView addSubview:self.fullScreenButton];
    
    // 布局控制视图
    [self.controlView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.equalTo(self);
        make.height.mas_equalTo(60);
    }];
    
    // 布局播放按钮
    [self.playPauseButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.controlView);
        make.leading.equalTo(self.controlView).offset(16);
        make.size.mas_equalTo(CGSizeMake(44, 44));
    }];
    
    // 布局进度条
    [self.progressSlider mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.controlView);
        make.leading.equalTo(self.playPauseButton.mas_trailing).offset(16);
        make.trailing.equalTo(self.fullScreenButton.mas_leading).offset(-16);
        make.height.mas_equalTo(30);
    }];
    
    // 布局全屏按钮
    [self.fullScreenButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.controlView);
        make.trailing.equalTo(self.controlView).offset(-16);
        make.size.mas_equalTo(CGSizeMake(44, 44));
    }];
}

- (void)loadVideo {
    if (!self.videoURL) return;
    
    // 重置播放器
    [self.player pause];
    self.player = nil;
    [self.playerLayer removeFromSuperlayer];
    self.playerLayer = nil;
    
    // 创建新的播放器
    self.player = [[AVPlayer alloc] initWithURL:self.videoURL];
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    self.playerLayer.frame = self.bounds;
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    self.playerLayer.zPosition = -1;
    self.playerLayer.contentsGravity = kCAGravityResizeAspectFill;
    self.playerLayer.cornerRadius = 8.0f;
    self.playerLayer.masksToBounds = YES;
    self.playerLayer.backgroundColor = [UIColor blackColor].CGColor;
    [self.layer addSublayer:self.playerLayer];
    
    // 开始播放
    [self.player play];
    [self showControls];
    [self startProgressTimer];
}

- (void)showControls {
    self.playPauseButton.hidden = NO;
    self.progressSlider.hidden = NO;
    self.fullScreenButton.hidden = NO;
    self.controlView.hidden = NO;
}

- (void)hideControls {
    self.playPauseButton.hidden = YES;
    self.progressSlider.hidden = YES;
    self.fullScreenButton.hidden = YES;
    self.controlView.hidden = YES;
}

- (void)startProgressTimer {
    [self.progressTimer invalidate];
    self.progressTimer = [NSTimer scheduledTimerWithTimeInterval:0.1
                                                          target:self
                                                        selector:@selector(updateProgress)
                                                        userInfo:nil
                                                         repeats:YES];
}

- (void)setupPlayerObservers {
    // 监听播放状态变化
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handlePlaybackStateChange)
                                                 name:AVPlayerItemDidPlayToEndTimeNotification
                                               object:nil];
    
    // 监听播放器状态变化
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handlePlayerItemStatusChange)
                                                 name:AVPlayerRateDidChangeNotification
                                               object:nil];
}

- (void)removePlayerObservers {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)handlePlayPause {
    if (self.player.rate == 0) {
        [self.player play];
        [self.playPauseButton setImage:[UIImage systemImageNamed:@"pause.fill"] forState:UIControlStateNormal];
    } else {
        [self.player pause];
        [self.playPauseButton setImage:[UIImage systemImageNamed:@"play.fill"] forState:UIControlStateNormal];
    }
}

- (void)handleProgressChange {
    if (self.player.currentItem && CMTimeGetSeconds(self.player.currentItem.duration) > 0) {
        CMTime seekTime = CMTimeMakeWithSeconds(
                                                self.progressSlider.value * CMTimeGetSeconds(self.player.currentItem.duration),
                                                self.player.currentItem.duration.timescale
                                                );
        [self.player seekToTime:seekTime];
    }
}

- (void)handleProgressEndChange {
    if (self.player.rate == 0) {
        [self.player play];
        [self.playPauseButton setImage:[UIImage systemImageNamed:@"pause.fill"] forState:UIControlStateNormal];
    }
}

- (void)handleFullScreen {
    self.isFullScreen = !self.isFullScreen;
    UIWindow *window = [UIApplication sharedApplication].delegate.window;
    if (self.isFullScreen) {
        self.originalFrame = self.frame;
        if (window) {
            self.frame = window.bounds;
            self.backgroundColor = [UIColor blackColor];
            self.playerLayer.frame = self.bounds;
            
            // 通知视图控制器更新状态栏
            if (window.rootViewController) {
                [window.rootViewController setNeedsStatusBarAppearanceUpdate];
            }
            
            if ([self.delegate respondsToSelector:@selector(videoPlayerViewDidChangeFullScreen:)]) {
                [self.delegate videoPlayerViewDidChangeFullScreen:YES];
            }
        }
    } else {
        if (CGRectGetWidth(self.originalFrame) > 0) {
            self.frame = self.originalFrame;
            self.backgroundColor = [UIColor clearColor];
            self.playerLayer.frame = self.bounds;
        }
        
        // 通知视图控制器更新状态栏
        if (window.rootViewController) {
            [window.rootViewController setNeedsStatusBarAppearanceUpdate];
        }
        
        if ([self.delegate respondsToSelector:@selector(videoPlayerViewDidChangeFullScreen:)]) {
            [self.delegate videoPlayerViewDidChangeFullScreen:NO];
        }
    }
}

- (void)updateProgress {
    if (self.player.currentItem && CMTimeGetSeconds(self.player.currentItem.duration) > 0) {
        CMTime currentTime = self.player.currentItem.currentTime;
        float progress = CMTimeGetSeconds(currentTime) / CMTimeGetSeconds(self.player.currentItem.duration);
        self.progressSlider.value = progress;
        
        // 视频播放完毕
        if (CMTimeGetSeconds(currentTime) >= CMTimeGetSeconds(self.player.currentItem.duration) - 0.5) {
            [self.playPauseButton setImage:[UIImage systemImageNamed:@"play.fill"] forState:UIControlStateNormal];
            [self.player pause];
        }
    }
}

- (void)handlePlaybackStateChange {
    // 视频播放完毕
    [self.playPauseButton setImage:[UIImage systemImageNamed:@"play.fill"] forState:UIControlStateNormal];
    [self.player pause];
}

- (void)handlePlayerItemStatusChange {
    if (self.player.currentItem) {
        switch (self.player.currentItem.status) {
            case AVPlayerItemStatusReadyToPlay:
                // 视频准备好播放
                [self showControls];
                break;
            case AVPlayerItemStatusFailed:
                // 加载失败
                [self hideControls];
                NSLog(@"视频加载失败");
                break;
            case AVPlayerItemStatusUnknown:
                // 状态未知
                [self hideControls];
                break;
            default:
                break;
        }
    }
}

- (void)play {
    [self.player play];
    [self.playPauseButton setImage:[UIImage systemImageNamed:@"pause.fill"] forState:UIControlStateNormal];
}

- (void)pause {
    [self.player pause];
    [self.playPauseButton setImage:[UIImage systemImageNamed:@"play.fill"] forState:UIControlStateNormal];
}

- (void)stop {
    [self.player pause];
    [self.player seekToTime:kCMTimeZero];
    [self.playPauseButton setImage:[UIImage systemImageNamed:@"play.fill"] forState:UIControlStateNormal];
}

- (void)setVideoURL:(NSURL *)videoURL {
    _videoURL = videoURL;
    [self loadVideo];
}

#pragma mark - 懒加载子视图
- (UIView *)controlView {
    if (!_controlView) {
        _controlView = [[UIView alloc] init];
        //        _controlView.backgroundColor = [UIColor blackColor].colorWithAlphaComponent(0.5);
        _controlView.hidden = YES;
    }
    return _controlView;
}

- (UIButton *)playPauseButton {
    if (!_playPauseButton) {
        _playPauseButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [_playPauseButton setImage:[UIImage systemImageNamed:@"play.fill"] forState:UIControlStateNormal];
        _playPauseButton.tintColor = [UIColor whiteColor];
        [_playPauseButton addTarget:self action:@selector(handlePlayPause) forControlEvents:UIControlEventTouchUpInside];
        _playPauseButton.hidden = YES;
    }
    return _playPauseButton;
}

- (UISlider *)progressSlider {
    if (!_progressSlider) {
        _progressSlider = [[UISlider alloc] init];
        _progressSlider.minimumValue = 0;
        _progressSlider.maximumValue = 1;
        _progressSlider.value = 0;
        _progressSlider.tintColor = [UIColor systemBlueColor];
        _progressSlider.thumbTintColor = [UIColor whiteColor];
        _progressSlider.minimumTrackTintColor = [UIColor systemBlueColor];
        _progressSlider.maximumTrackTintColor = [UIColor lightGrayColor];
        [_progressSlider addTarget:self action:@selector(handleProgressChange) forControlEvents:UIControlEventValueChanged];
        [_progressSlider addTarget:self action:@selector(handleProgressEndChange) forControlEvents:UIControlEventTouchUpInside];
        _progressSlider.hidden = YES;
    }
    return _progressSlider;
}

- (UIButton *)fullScreenButton {
    if (!_fullScreenButton) {
        _fullScreenButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [_fullScreenButton setImage:[UIImage systemImageNamed:@"expand"] forState:UIControlStateNormal];
        _fullScreenButton.tintColor = [UIColor whiteColor];
        [_fullScreenButton addTarget:self action:@selector(handleFullScreen) forControlEvents:UIControlEventTouchUpInside];
        _fullScreenButton.hidden = YES;
    }
    return _fullScreenButton;
}

@end
